package gdut.edu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gdut.edu.Mapper.UserMapper;
import gdut.edu.domain.ResponseResult;
import gdut.edu.domain.User;
import gdut.edu.domain.UserLogin;
import gdut.edu.service.LoginService;
import gdut.edu.utils.JwtUtil;
import gdut.edu.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    public ResponseResult login(User user) {
//        AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

//        如果认证没有通过，给出用户提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
//        认证通过，使用userid生成一个jwt，jwt存入ResponseResult返回
        UserLogin userLogin = (UserLogin) authenticate.getPrincipal();
        String userId = userLogin.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);


//        把完整的用户信息存入redis，userid为key
        redisCache.setCacheObject("login:"+userId,userLogin);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
//        获取SecurityContextHolder中的userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLogin userLogin = (UserLogin) authentication.getPrincipal();
        Long userId = userLogin.getUser().getId();
//        删除redis中user的信息
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"注销成功");
    }
}
